<?php
require_once 'config.php';
require_once 'Utils.php';
class JSSDK {
	private $appId;
	private $appSecret;
	private $curl;

	public function __construct() {
		$this -> appId = APP_ID;
		$this -> appSecret = APP_SECRET;
	}

	public function setCurl($u) {
		$this -> curl = $u;
	}

	/*public function __construct($appId, $appSecret) {
	 $this -> appId = isset($appId) ? $appId : APP_ID;
	 $this -> appSecret = isset($appSecret) ? $appSecret : APP_SECRET;
	 }*/
	public function getAppId() {
		return $this -> appId;
	}

	public function getAppSecret() {
		return $this -> appSecret;
	}

	/**
	 * @description 使用加密算法获取signature
	 * 注意事项:
	 * 	1、签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。
	 *	2、签名用的url必须是调用JS接口页面的完整URL。
	 *	3、出于安全考虑，开发者必须在服务器端实现签名的逻辑。
	 */
	public function getSignPackage() {
		/**
		 * @description 说明
		 * 	1、access_token每日只有2000次调用，因此也需要缓存,有效期为两个小时
		 * 	2、access_token用于获取jsapi_ticket，公众号用于调用微信JS接口的临时票据。正常情况下，jsapi_ticket的有效期为7200秒，需要进行缓存
		 * 	3、参与签名的字段包括noncestr（随机字符串）, 有效的jsapi_ticket, timestamp（时间戳）, url（当前网页的URL，不包含#及其后面部分） 。
		 * 	4、对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串string1。
		 * 	5、这里需要注意的是所有参数名均为小写字符。对string1作sha1加密，字段名和字段值都采用原始值，不进行URL 转义。
		 * 	6、noncestr=random_str	jsapi_ticket=get_jsapi_ticket	timestamp=time()
		 * 	7、url='http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"],如：http://mp.weixin.qq.com?params=value
		 * 	8、sha1签名：sha1($str)
		 * 	9、待签名字符串(注意字符串顺序)：jsapi_ticket={$jsapi_ticket}&noncestr={$noncestr}&timestamp={$timestamp}&url={$url}
		 */

		$jsapiTicket = $this -> getJsApiTicket();

		if (!isset($this -> curl) || empty($this -> curl)) {
			// 注意 URL 一定要动态获取，不能 hardcode.
			$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
			$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		} else {
			$url = $this -> curl;
		}

		$timestamp = time();
		$nonceStr = $this -> createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);

		$signPackage = array("appId" => $this -> appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string);
		return $signPackage;
	}

	/**
	 * @description 创建随机字符串NonceStr
	 * @param {$length} 随机字符串长度，默认16位
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	/**
	 * @description 获取JsApiTicket
	 */
	private function getJsApiTicket() {
		// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
		$data = json_decode(file_get_contents("common/jsapi_ticket.json"));
		if ($data -> expire_time < time()) {
			$accessToken = $this -> getAccessToken();
			// 如果是企业号用以下 URL 获取 ticket
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode(Utils::curl_get($url));
			$ticket = $res -> ticket;
			if ($ticket) {
				$data -> expire_time = time() + 7000;
				$data -> jsapi_ticket = $ticket;
				$fp = fopen("common/jsapi_ticket.json", "w");
				fwrite($fp, json_encode($data));
				fclose($fp);
			}
		} else {
			$ticket = $data -> jsapi_ticket;
		}

		return $ticket;
	}

	/**
	 * @description 获取AccessToken
	 */
	public function getAccessToken() {
		// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
		$data = json_decode(file_get_contents("common/access_token.json"));
		if ($data -> expire_time < time()) {
			// 如果是企业号用以下URL获取access_token
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
			$res = json_decode(Utils::curl_get($url));
			$access_token = $res -> access_token;
			if ($access_token) {
				$data -> expire_time = time() + 7000;
				$data -> access_token = $access_token;
				$fp = fopen("common/access_token.json", "w");
				fwrite($fp, json_encode($data));
				fclose($fp);
			}
		} else {
			$access_token = $data -> access_token;
		}
		return $access_token;
	}

	public function get_lotteryinfo($parameters_addlotteryinfo) {
		$access_tokenStr = $this -> getAccessToken();
		$addlotterinfo_url = "https://api.weixin.qq.com/shakearound/lottery/addlotteryinfo?access_token={$access_tokenStr}&use_template=2";
		$arr = Utils::curl_post($addlotterinfo_url, json_encode($parameters_addlotteryinfo));
		return $arr;
	}

	/**
	 * 获取授权AccessToken信息
	 * @param {String} code 授权页面返回的code编码，授权通过时才有，不通过是没有
	 * @return {Object}
	 * {
	 *	"access_token":"ACCESS_TOKEN",
	 *	"expires_in":7200,
	 *	"refresh_token":"REFRESH_TOKEN",
	 *	"openid":"OPENID",
	 *	"scope":"SCOPE",
	 *	"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
	 *	}
	 */
	public function getAuthorizeAccessToken($code) {
		$oauth_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APP_ID."&secret=".APP_SECRET."&code={$code}&grant_type=authorization_code";
		$arr = Utils::curl_get($oauth_url);
		return $arr;
	}

	/**
	 * 授权后拉取用户信息
	 */
	public function getUserInfoByOpenid($access_token, $openid) {
		$oauth_userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";

		//print_r("oauth_userinfo_url:$oauth_userinfo_url<br />");
		$arr = Utils::curl_post($oauth_userinfo_url,null);
		//$oauth_userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
		//$json = file_get_contents($oauth_userinfo_url);
		//return $json;
		//获取微信用户基本信息
		// 创建一个cURL资源
		//$ch = curl_init();

		// 设置URL和相应的选项
		//curl_setopt($ch, CURLOPT_URL, $oauth_userinfo_url);
		//curl_setopt($ch, CURLOPT_HEADER, 0);

		// 抓取URL并把它传递给浏览器
		//$arr = curl_exec($ch);
		//print_r($arr);
		// 关闭cURL资源，并且释放系统资源
		//curl_close($ch);
		return $arr;
	}

	/**
	 * 获取用户基本信息
	 */
	public function getUserBaseInfo($openid) {
		$access_tokenStr = $this -> getAccessToken();
		$oauth_userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_tokenStr}&openid={$openid}&lang=zh_CN";
		$arr = Utils::curl_get($oauth_userinfo_url);
		return $arr;
	}

	/**
	 * 创建自定义菜单
	 */
	public function createMenu() {
		$access_tokenStr = $this -> getAccessToken();
		$createmenu_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_tokenStr}";
		$data = '{
    "button": [
        {
            "name": "买个安心", 
            "sub_button": [
                {
                    "type": "view", 
                    "name": "平安家政险", 
                    "url":"http://pro.mdg-app.com:7001/duoduo-policy/gzh.php"
                }, 
                {
                    "type": "view", 
                    "name": "家政险购买专区", 
                    "url":"http://pro.mdg-app.com:7001/duoduo-policy/gzh.php"
                }
            ]
        },{
            "name": "问问小编", 
            "sub_button": [
                {
                    "type": "view", 
                    "name": "家有保姆", 
                    "url":"http://pro.mdg-app.com:7001/duoduo-policy/gzh.php"
                }
            ]
        }, {
           "name":"为我服务",
           "sub_button":[
           {	
               "type":"view",
               "name":"帮帮我",
               "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid='.APP_ID.'&redirect_uri=http%3A%2F%2Fmlop.ngrok.natapp.cn%2Fk-weixin%2Fgzh.php%3Furl%3Dhttp%3A%2F%2Fmlop.ngrok.natapp.cn%2Fduoduo-policy%2Fgzh.php&response_type=code&scope=snsapi_userinfo&state=31265#wechat_redirect"
            },
            {
               "type":"view",
               "name":"算算看",
               "url":"http://pro.mdg-app.com:7001/duoduo-policy/policylistwx.html"
            },
            {
               "type":"click",
               "name":"关于我们",
               "key":"V1001_GOOD"
            }]
       }
    ]
}';
		//"url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx37b563f7d963825e&redirect_uri=http%3A%2F%2Fmlopwx.duapp.com%2Fgzh.php%3Furl%3Dhttp%3A%2F%2Fmlop.ngrok.natapp.cn%2Fduoduo-policy%2Fgzh.php&response_type=code&scope=snsapi_userinfo&state=31265#wechat_redirect"
		$arr = Utils::curl_post($createmenu_url, $data);
		$res['arr'] = $arr;
		$res['data'] = $data;
		//将地址参数返回打印
		return $res;
	}

	/**
	 * @description 发送http get请求
	 */
	/*private function httpGet($url) {
	 $curl = curl_init();
	 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	 curl_setopt($curl, CURLOPT_TIMEOUT, 500);
	 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	 curl_setopt($curl, CURLOPT_URL, $url);

	 $res = curl_exec($curl);
	 curl_close($curl);

	 return $res;
	 }*/

}
